<template>
	<view style="height: 100vh; background: #fff">
		<view class="container" v-if="isLogin==1">
			<view class="login">
				<div class="lg">
					<image src="../../static/image/logo.png" alt="" class="loginLogo" />
				</div>
			</view>
			<view class="form">
				<button class="loginBtn" :disabled="allChecked ? false : true" @click="jingMoLogin"
					:class="!allChecked ? 'noClick' : ''" >
					快速登录
				</button>
				<view class="closeLogin" @click="closeLogin">取消登录</view>
			</view>
			<view class="tips">
				<label class="radio" @click="changeAll">
					<radio class="radio" :value="allChecked" :checked="allChecked" color="#D0A564"
						style="transform: scale(0.7)" />
					<text>已阅读并同意智装通平台<text class="tipColor">《用户协议》</text>及隐私政策</text>
				</label>
			</view>
		</view>
		<view class="container" v-if="isLogin==2">
			<view class="login">
				<div class="lg">
					<image src="../../static/image/logo.png" alt="" class="loginLogo" />
				</div>
			</view>
			<view class="form">
				<button class="loginBtn" :disabled="allChecked ? false : true" open-type="getPhoneNumber"
					:class="!allChecked ? 'noClick' : ''" @getphonenumber="getPhoneNumber">
					绑定手机号
				</button>
				<view class="closeLogin" @click="closeLoginToHome">跳过</view>
			</view>
		</view>
		<view class="containers" v-if="isLogin==3">
			<view class="login">
				<div class="lg">
					<image src="../../static/image/logo.png" alt="" class="loginLogo" />
				</div>
			</view>
			<view class="form">
				<up-form labelPosition="top" :model="userInfo" :rules="rules" ref="uForm" class="forms">
					<up-form-item label="手机号" prop="phone" ref="item1" border="none">
						<up-input v-model="userInfo.phone" border="none" class="one" disabled maxlength="11"></up-input>
					</up-form-item>
					<up-form-item label="验证码" prop="code" ref="item1">
						<up-input v-model="userInfo.code" border="none" class="two" maxlength="6">
							<template #suffix>
								<view class="getPhoneCode" v-if="!getCodeShow" @click="getCode(userInfo.phone)">获取验证码
								</view>
								<view class="getPhoneCode" v-if="getCodeShow">{{ timer }}秒重新获取</view>
							</template>
						</up-input>
					</up-form-item>
				</up-form>
				<view class="tipInfo">
					提示：您选择的手机号已绑定其他微信账号！如需解绑原有微信并重新绑定，请完成短信验证！
				</view>
				<button class="loginBtn" @click="saveInfo">验证并重新绑定微信</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		wx_small_login,
		small_phone,
		get_oss_url,
		getCodeRequst,
		save,
	} from "@/api/login.js";
	import {
		ref
	} from "vue";
	import {
		get_qr
	} from "@/api/warm.js";
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app";
	import {
		redirectToOriginalPage
	} from "@/utils/auth.js";
	// 是否同意协议的状态
	const agreeToTerms = ref(false); // 默认未选中
	const wxcCode = ref("");
	const allChecked = ref(false); //隐私协议默认
	const showPhone = ref(false);
	const userInfo = ref({
		phone: "",
		code: "",
		user_id: "",
	});

	const rules = {
		phone: [{
				type: "string",
				required: true,
				max: 11,
				message: "请输入正确手机号",
				trigger: ["blur", "change"],
			},
			{
				pattern: /^1[3-9]\d{9}$/,
				message: "手机号格式不正确",
				trigger: "blur",
			},
		],
		code: {
			type: "string",
			max: 6,
			required: true,
			message: "请输入验证码",
			trigger: ["blur", "change"],
		},
	};
	//手机号未被占用
	const isLogin = ref(1);

	const sceneType = ref("");

	onShow(() => {
    allChecked.value = false
		sceneType.value = uni.getStorageSync("sceneType");
		if (!allChecked.value) {
			uni.showToast({
				icon: "none",
				title: "请先同意用户协议",
			});
		}
	});
	//静默登录
	const jingMoLogin = async () => {
		// 检查是否同意协议
		if (!allChecked.value) {
			uni.showToast({
				icon: "none",
				title: "请先同意用户协议",
			});
			return;
		}
		const loginRes = await uni.login({
			provider: "weixin",
		});
		if (loginRes.code) {
			const res = await wx_small_login({
				code: loginRes.code,
			});
			const datas = res.data.userinfo;
			uni.setStorageSync("token", res.data.userinfo.token);
			uni.setStorageSync("useInfo", res.data.userinfo);
			if (!datas.phone) {
				isLogin.value = 2;
			} else {
				isLogin.value = 1;
				handleLoginSuccess();
			}
				
		} else {
			uni.showToast({
				icon: "none",
				title: "授权失败",
			});
		}
	};

	const closeLoginToHome = () => {
    allChecked.value = false
		isLogin.value =1
		uni.switchTab({
			url: "/pages/home/index",
		});
	};
	
	const closeLogin = () => {
		handleLoginSuccess('1');
	};
	// 选择隐私协议
	const changeAll = () => {
		allChecked.value = !allChecked.value;
	};
	let timer = ref(60);
	let t = null;
	let getCodeShow = ref(false);
	//获取验证码
	const getCode = async (phone) => {
		let res = await getCodeRequst({
			phone: phone,
			scene: "13",
			extend: userInfo.value.user_id,
		});
		uni.showToast({
			icon: "none",
			title: res.msg,
		});
		if (res.code == 1) {
			getCodeShow.value = true;
			if (t) clear();
			t = setInterval(() => {
				timer.value--;
				if (timer.value === 0) clear();
			}, 1000);
		} else {
			getCodeShow.value = false;
		}
		console.log(res.data);
	};

	const clear = () => {
		clearInterval(t);
		timer.value = 60;
		getCodeShow.value = false;
		t = null;
	};
	// 获取手机号
	const getPhoneNumber = (e) => {
		
		// 注意：目前该接口针对非个人开发者，且完成了认证的小程序开放（不包含海外主体）。需谨慎使用，若用户举报较多或被发现在不必要场景下使用，微信有权永久回收该小程序的该接口权限。
		if (e.detail.errMsg == "getPhoneNumber:ok") {
			loginPhone(e.detail.code);
		} else {
			handleLoginSuccess('1');
			console.log("用户点击了拒绝");
		}
	};
	//通过微信code 获取信息
	const loginPhone = async (code) => {
		const res = await small_phone({
			code,
		});
		if (res.code == 0) {
			isLogin.value = 3;
			uni.showToast({
				icon: "none",
				title: res.msg,
			});
			uni.setStorageSync("token", "");
			uni.setStorageSync("useInfo", "");
		} else {
			if (res.data.hasOwnProperty("phone")) {
				isLogin.value = 3;
				userInfo.value.phone = res.data.phone;
				userInfo.value.user_id = res.data.user_id;
			}
			if (res.data.hasOwnProperty("userinfo")) {
				isLogin.value = 2;
				uni.setStorageSync("token", res.data.userinfo.token);
				uni.setStorageSync("useInfo", res.data.userinfo);
				// uni.switchTab({
				// 	url: '/pages/home/index'
				// })
				//   if (sceneType.value) {
				//     uni.redirectTo({
				//       url: "/pages/common/index",
				//     });
				//   } else {
				//     uni.switchTab({
				//       url: "/pages/home/index",
				//     });
				//   }
				handleLoginSuccess('2');
			}
		}
	};
	const uForm = ref();
	//通过微信code 获取信息
	const saveInfo = async () => {
		console.log("baocun");
		if (userInfo.value.code == "") {
			uni.showToast({
				icon: "none",
				title: "请输入验证码",
			});
			return;
		}
		// uForm.value.validate(async (valid) => {
		// 	if (valid) {
		// console.log(valid)
		let obj = {
			code: userInfo.value.code,
			user_id: userInfo.value.user_id,
		};
		const res = await save(obj);
		if (res.code == 0) {
			uni.showToast({
				icon: "none",
				title: res.msg,
			});
			isLogin.value = 3;
			uni.setStorageSync("token", "");
			uni.setStorageSync("useInfo", "");
		} else {
			isLogin.value = 3;
			uni.setStorageSync("token", res.data.userinfo.token);
			uni.setStorageSync("useInfo", res.data.userinfo);
			handleLoginSuccess('2');
			// uni.switchTab({
			// 	url: '/pages/home/index'
			// })
			// if (sceneType.value) {
			//   uni.redirectTo({
			//     url: "/pages/common/index",
			//   });
			// } else {
			//   uni.switchTab({
			//     url: "/pages/home/index",
			//   });
			// }
		}
		// } else {
		// 	console.log('验证失败');
		// }
		// });
	};
	const sceneData = ref("");
	const handleLoginSuccess = (code) => {
    allChecked.value = false
		sceneData.value = uni.getStorageSync("sceneData"); //是否扫码 有储存的值
		console.log("login 页面的 扫码参数", sceneData.value);
		if (sceneData.value !== "") {
			uni.reLaunch({
				url: "/pages/common/index",
			});
		} else {
			// 登录成功后跳转回原页面
			redirectToOriginalPage(code);
		}
	};
</script>

<style lang="less" scoped>
	.closeLogin {
		margin-top: 45rpx;
		text-align: center;
		color: #333;
	}

	.container {
		height: 100%;
		padding: 432rpx 30rpx 100rpx;
		display: flex;
		flex-direction: column;
		background-image: url("https://zzt-pub.oss-cn-wuhan-lr.aliyuncs.com/clientImg/loginBg.png");
		background-size: cover;
		background-repeat: no-repeat;
		height: 877rpx;

		.login {
			width: 100%;
			display: flex;
			justify-content: center;

			.lg {
				height: 100%;
				display: flex;
				justify-content: center;

				.loginLogo {
					width: 260rpx;
					height: 130rpx;
				}
			}
		}

		.form {
			margin-top: 115rpx;
			display: flex;
			flex-wrap: wrap;
			align-content: center;
			justify-content: center;

			.loginBtn {
				display: block;
				border-radius: 10rpx;
				width: 100%;
				line-height: 88rpx;
				height: 88rpx;
				font-size: 32rpx;
				color: #fff;
				text-align: center;
				cursor: pointer;
				background: linear-gradient(115deg, #f2bd6f 0%, #cca05f 100%);
			}
		}

		.tips {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 22rpx;
			position: absolute;
			bottom: 80rpx;
			left: 0;
		}

		.tipColor {
			color: #d0a564;
		}

		.noClick {
			color: #333 !important;
			background: #f5f5f5 !important;
		}
	}

	::v-deep .uni-radio-input {
		width: 22rpx !important;
		height: 22rpx !important;
		margin-right: 6rpx !important;
		font-size: 22rpx !important;
	}

	::v-deep .u-button {
		color: #cca05f;
		margin-top: 40rpx;
		width: 220rpx !important;
	}

	::v-deep .u-button:active {
		background-color: #fff;
	}

	.containers {
		height: 100%;
		padding: 300rpx 30rpx 100rpx;
		display: flex;
		flex-direction: column;
		background-image: url("https://zzt-pub.oss-cn-wuhan-lr.aliyuncs.com/clientImg/loginBg.png");
		background-size: cover;
		background-repeat: no-repeat;
		height: 877rpx;

		.getPhoneCode {
			font-weight: 400;
			font-size: 30rpx;
			color: #d0a564;
			cursor: pointer;
			background: #ffffff;
			padding-right: 20rpx;
		}

		.login {
			width: 100%;
			display: flex;
			justify-content: center;

			.lg {
				height: 100%;
				display: flex;
				justify-content: center;

				.loginLogo {
					width: 260rpx;
					height: 130rpx;
				}
			}
		}

		.form {
			margin-top: 68rpx;
			display: flex;
			flex-wrap: wrap;
			align-content: center;

			.forms {
				display: flex;
				flex: 1;
				flex-direction: column;
				width: calc(100vw - 30px);
			}

			.loginBtn {
				display: block;
				border-radius: 10rpx;
				width: 100%;
				line-height: 88rpx;
				height: 88rpx;
				font-size: 32rpx;
				color: #fff;
				text-align: center;
				cursor: pointer;
				background: linear-gradient(115deg, #f2bd6f 0%, #cca05f 100%);
			}
		}

		.tipInfo {
			width: 100%;
			font-weight: 400;
			font-size: 24rpx;
			color: #999999;
			margin-bottom: 80rpx;
		}
	}

	::v-deep .u-form-item {
		width: calc(100vw - 30px) !important;
	}

	::v-deep .u-form-item__body__left {
		width: calc(100vw - 30px) !important;
	}

	::v-deep .u-input {
		margin-top: 18rpx !important;
		width: calc(100vw - 30px) !important;
		height: 88rpx;
		background: #ffffff;
		border-radius: 10rpx 10rpx 10rpx 10rpx;
		border: 2rpx solid #e2e2e2;
		padding-left: 20rpx;
	}

	::v-deep .u-input__content {
		padding-left: 20rpx;
	}
</style>